package de.mouseless.csv2sql.parsers;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;

import de.mouseless.csv2sql.model.DDLModel;

public class CSVModelParser {
   private File csvFile;
   private DDLModel model = new DDLModel();
   private ParserContext context = new ParserContext(model);

   public CSVModelParser(File csvFile) {
      super();
      this.csvFile = csvFile;
   }
   
   public DDLModel parseCSVModel() throws IOException {
      LineIterator it = FileUtils.lineIterator(csvFile, "UTF-8");
      List<List<String>> linesForOneTable = null;
      try {
        while (it.hasNext()) {
          String line = it.nextLine();
          if(line.toLowerCase().startsWith("table")) {
             if(linesForOneTable!=null) {
                TableParser colParser = new TableParser(linesForOneTable);
                model.addTable(colParser.parseTable(context));
             }

             linesForOneTable = new ArrayList<List<String>>();
          }
          if(linesForOneTable!=null) {
             linesForOneTable.add(Arrays.asList(line.split("\\s*;\\s*")));
          }
          
        }
      } finally {
        LineIterator.closeQuietly(it);
      }
      return null;
   }

}
